/**
** \file       command.c
**
** \brief      this function parse the command rule
**
** \author     Ben M'rad Hanna, Laterem Hamza, Boillot Ulysse et De Olivera
**             Guillaume and Nguyen Viet Dung
**
** \version    1.0
**
** \date       28 Novembre 2010
**
*/

#include "rules.h"

static s_command            *my_malloc1(s_command           *cmd)
{
  cmd->smp_cmd = calloc(1, sizeof (s_smp_cmd));
  cmd->sh_cmd = calloc(1, sizeof (s_sh_cmd));
  cmd->funcdec = calloc(1, sizeof (s_funcdec));

  return (cmd);
}

static s_command        *my_free1(s_command             *cmd,
                                  int                   n)
{
  if (n != 1)
    {
      free_smp_cmd(cmd->smp_cmd);
      cmd->smp_cmd = NULL;
    }

  if (n != 2)
    {
      free(cmd->funcdec);
      cmd->funcdec = NULL;
    }

  if (n != 3)
    {
      free_sh_cmd(cmd->sh_cmd);
      cmd->sh_cmd = NULL;
    }

  return (cmd);
}

s_command                   *rule_command(s_command         *cmd)
{
  if (g_data->lexer == NULL)
    return (NULL);

  cmd = my_malloc1(cmd);

  if (rule_shell_command(cmd->sh_cmd) == NULL)
    {
      if (rule_funcdec(cmd->funcdec) == NULL)
	{
	  if (rule_simple_command(cmd->smp_cmd) != NULL)
	    return (my_free1(cmd, 1));
	}
      else
	return (my_free1(cmd, 2));
    }
  else
    return (my_free1(cmd, 3));

  return (my_free1(cmd, 4));
}
